package com.atguigu.gmall.common.config.executor;

import com.atguigu.gmall.common.config.executor.properties.ThreadPoolProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;


@Slf4j
//开启属性绑定
@EnableConfigurationProperties(ThreadPoolProperties.class) //1、开启绑定 2、组件放到容器中
/*
* 不能使用@Component，因为在别的包没有ThreadPoolProperties类
*
* 1. 但是可以在ThreadPoolExecutorAutoConfiguration类中，添加Bean
*   @Bean
*   public ThreadPoolProperties poolProperties(){
*         return new ThreadPoolProperties();
    }
*
* 2. 使用@EnableConfigurationProperties注解
*
* 绑定ThreadPoolProperties.class
* */

@Configuration
public class ThreadPoolExecutorAutoConfiguration {


//    @Bean
//    public ThreadPoolProperties poolProperties(){
//        return new ThreadPoolProperties();
//    }


//    @Autowired
//    ThreadPoolProperties poolProperties;


    @Bean
    ThreadPoolExecutor executor(ThreadPoolProperties poolProperties) {
        /**
         * int corePoolSize,
         * int maximumPoolSize,
         * long keepAliveTime,
         * TimeUnit unit,
         * BlockingQueue<Runnable> workQueue,
         * ThreadFactory threadFactory, 默认
         * RejectedExecutionHandler handler
         */
        log.info("正在给容器中准备自定义线程池.....");
        return new ThreadPoolExecutor(
                poolProperties.getCore(),
                poolProperties.getMax(),
                poolProperties.getKeepAliveTime(),
                poolProperties.getUnit(),
                new LinkedBlockingQueue<>(poolProperties.getWorkQueueSize()),
                new ThreadPoolExecutor.CallerRunsPolicy()
        );
    }
}
